package com.kzd.btgame.main.mine

import android.view.LayoutInflater
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.LifecycleOwner
import com.kzd.btgame.R
import com.kzd.btgame.custom.setTransitionStatus
import com.kzd.btgame.databinding.ActivityMineAddressBinding
import com.kzd.btgame.jetpack.vm.AddressViewModel
import com.module.lemlin.app.OwnerStatusBar
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewBindingActivity
import com.module.lemlin.owner.ownerViewModel

class MineAddressActivity : OwnerViewBindingActivity<ActivityMineAddressBinding>() {

    private val mViewModel: AddressViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater) -> ActivityMineAddressBinding
        get() = ActivityMineAddressBinding::inflate

    override fun initStatusBar(statusBar: OwnerStatusBar) {
        statusBar.run {
            addView = mViewBinding.flMineAddressBar
            barColor = R.color.white
        }
        super.initStatusBar(statusBar)
    }

    override fun initView() {
        supportFragmentManager(AddressListFragment.newInstance(), isToBackStack = false)
    }

    override fun initViewMode() {
        mViewModel.addressInfoLiveData.observe(this as LifecycleOwner, { action ->
            supportFragmentManager(AddressEditFragment.newInstance(action))
        })

        mViewModel.userAddressKeepLiveData.observe(this as LifecycleOwner, { response ->
            this.setTransitionStatus(response)
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            mViewModel.userAddress()
            onBackPressed()
        })
    }

    private fun supportFragmentManager(fragment: Fragment, isToBackStack: Boolean = true) {
        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (isToBackStack) {
            transaction.setCustomAnimations(
                R.animator.slide_right_in, R.animator.slide_left_out,
                R.animator.slide_left_in, R.animator.slide_right_out
            )
            transaction.replace(R.id.flMineAddressBody, fragment)
            transaction.addToBackStack(null)
        } else {
            transaction.replace(R.id.flMineAddressBody, fragment)
        }
        transaction.commit()
    }
}